import React, { useState, useEffect } from "react";
import { Form, Row, Col, Checkbox, Button, Card, Dropdown, Menu, message, Divider, Space } from "antd";
import { DownOutlined } from "@ant-design/icons";
import hcpcmdb from "@/data/hcpcmdb";
import request from "@/utils/request";
// import mock from "@/data/mock/filter.json";
import './HcpHeaderFilter.less';
import { useCloudInfo } from '@/components'

const CLOUD_MAP = [
  { cloudCode: 'unifcloud', cloudName: '联通云' },
  { cloudCode: 'tencentcloud', cloudName: '腾讯云' },
  { cloudCode: 'alipubliccloud', cloudName: '阿里云' },
  { cloudCode: 'huaweipubliccloud', cloudName: '华为云' }
]
const FormItem = Form.Item
const formItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 24,
      offset: 0,
    },
  },
};
const HcpHeaderFilter = (props) => {
  const { handleHeadFilterSubmit, width } = props
  const [form] = Form.useForm();
  const [dropDownsVisible, setDropDownsVisible] = useState([])
  const [accountList, setAccountList] = useState([])
  const { cloudList, getNameByCode, getIdByCode } = useCloudInfo();

  const [, forceF] = useState({});
  function forceUpdate() {
    forceF({});
  }

  useEffect(() => {
    if (!cloudList.length > 0) return;
    getAccountList()
  }, [cloudList]);

  const onTotalCheckBoxChange = (e, cloudCode) => {
    let formVal = form.getFieldsValue()
    let cloudAccList = formVal[cloudCode]
    if (e.target.checked) {//全选
      cloudAccList = cloudAccList.map(item => true)
    } else {
      cloudAccList = cloudAccList.map(item => false)
    }
    let dataNew = { ...formVal, [cloudCode]: cloudAccList }
    form.setFieldsValue(dataNew)
    forceUpdate()
  }

  const onRowCheck = (e, cloud) => {
    const list = getSelectedList(cloud)
    const total = getTotalList(cloud)
    // if (!e) {
    let dataNew = { ...form.getFieldsValue(), [`${cloud.cloudCode}All`]: list === total }
    form.setFieldsValue(dataNew);
    forceUpdate();
    // }
  }
  // 默认全选
  const handleAllChecked = (data) => {
    let formObj = {}
    data.forEach((cloud, index) => {
      if (cloud.accounts) {
        let cloudCode = cloud.cloudCode
        formObj[`${cloudCode}All`] = true
        formObj[cloudCode] = new Array(cloud.accounts?.length).fill(true)
      }
    })
    form.setFieldsValue(formObj)
    handleSubmit(formObj, data)
  }
  const getAccountList = async () => {
    try {
      const res = await request({
        ...hcpcmdb.queryAccountSaas,
        params: {
          status: 1,
          cloudType:'public',
        },
      });
      // setLoading(false);
      if (res && res?.code === 200) {
        res.data?.map((i) => (i.key = i.id));
        const data = process(res.data || [])
        setAccountList(data)
        setDropDownsVisible((new Array(data.length)).fill(false))
        handleAllChecked(data)
      } else {
        setAccountList([])
      }
    } catch (error) {
      console.log("getAccountList -> error", error);
    }
  };

  function process(res) {
    const cloudMap = new Map()
    res.forEach(e => {
      if (cloudMap.has(e.cloudCode)) {
        const list = cloudMap.get(e.cloudCode)
        const newList = [...list, e]
        cloudMap.set(e.cloudCode, newList)
      } else {
        cloudMap.set(e.cloudCode, [e])
      }
    })
    let ress = [...CLOUD_MAP]
    for (const [key, value] of cloudMap) {
      let index = CLOUD_MAP.findIndex(item => item.cloudCode === key)
      if (index !== -1) {
        ress[index] = {
          cloudCode: key,
          cloudName: getNameByCode(key),
          accounts: value
        }
      }
    }
    return ress
  }

  const onVisibleChange = (visible, cloudCode, cloudIndex) => {
    let temp = [...dropDownsVisible]
    temp.splice(cloudIndex, 1, visible)
    setDropDownsVisible(temp)
    if (visible) {
      let cloud = accountList.find(item => {
        return item.cloudCode === cloudCode
      })
      // if (!cloud.accounts?.length) {
      //   message.error(`${cloud.cloudName}下暂无云账号信息，请先去维护云账号信息`)
      // }
    }
  }

  const handleSubmit = (propData, propAccList) => {
    const formVal = propData || form.getFieldsValue();
    const accList = propAccList || accountList
    const result = {};
    Object.keys(formVal).forEach(cloud => {
      if (cloud.indexOf('All') === -1 && formVal[cloud]) {//形式3
        let exist = false
        let idList = []
        formVal[cloud].forEach((accountTag, accountIndex) => {
          if (accountTag) {
            exist = true
            idList.push(accList.find(i => i.cloudCode === cloud)?.accounts[accountIndex]?.id)
          }
        })
        if (exist) {
          result[cloud] = idList;
        }
      }
    })
    const newFilters = {}
    for (const [key, value] of Object.entries(result)) {
      newFilters[getIdByCode(key)] = value;
    }
    if (JSON.stringify(newFilters) === '{}') {
      message.warning('云账号不能为空')
      return
    }
    handleHeadFilterSubmit(newFilters)
  }
  const getAccountSelectNum = (cloudCode) => {
    let length = 0
    cloudCode && form.getFieldValue(cloudCode)?.forEach(item => {
      if (item) length++
    })
    return length
  }

  const getAccountSelectAll = (cloud) => {
    let length = getSelectedList(cloud);
    let totalLength = getTotalList(cloud);
    if (length === totalLength) return false;
    return !!length && length < totalLength;
  }

  // 根据cloud 拿到已选择的list长度
  const getSelectedList = ({ cloudCode }) => form.getFieldValue(cloudCode)?.reduce((pre, cur) => cur ? pre += 1 : pre, 0);
  // 根据cloud 拿到总长度
  const getTotalList = ({ accounts }) => accounts?.length || 0;

  return (
    <Card bordered={false} className="hcp-header-filter" style={{ width: width || '85%', minHeight: 85 }}>
      <Form form={form}>
        <Row gutter={8}>
          {
            accountList.length ? accountList.map((cloud, cloudIndex) => {
              return <Col span={5} key={cloudIndex}>
                <Dropdown
                  visible={dropDownsVisible[cloudIndex]}
                  onVisibleChange={(visible) => { onVisibleChange(visible, cloud.cloudCode, cloudIndex) }}
                  getPopupContainer={(triggerNode) => triggerNode.parentElement}
                  forceRender={true}
                  overlay={
                    <div className='hcp-header-filter-droplist' >
                      {!cloud.accounts?.length ? <div style={{ padding: '5px 10px' }}>
                        {cloud.cloudName}下暂无云账号信息，请先去维护云账号信息
                      </div> : <>
                        <Menu className="hcp-header-filter-content" forceSubMenuRender={true}>
                          {cloud.accounts?.map((item, index) => {
                            return (
                              <Menu.Item key={item.id} title={`${item.tenantName}(${item.accessKey})`} >
                                <FormItem
                                  name={[cloud.cloudCode, index]}
                                  valuePropName='checked'
                                  noStyle={true}
                                  initialValue={false}
                                >
                                  <Checkbox id={item.id} onChange={e => onRowCheck(e, cloud)}>
                                    {`${item.tenantName}(${item.accessKey || ''})`}
                                  </Checkbox>
                                </FormItem>
                              </Menu.Item>
                            )
                          })}
                        </Menu>
                        <div className='ul-footer'>帐号总数：{cloud.accounts?.length}个</div>
                      </>}
                    </div>}>
                  <Row>
                    <Col span={4}>
                      <FormItem
                        name={`${cloud.cloudCode}All`}
                        valuePropName='checked'
                        {...formItemLayout}
                      >
                        <Checkbox indeterminate={getAccountSelectAll(cloud)}
                          disabled={!(cloud.accounts?.length > 0)}
                          defaultChecked={false}
                          onChange={(e) => { onTotalCheckBoxChange(e, cloud.cloudCode) }} />
                      </FormItem>
                    </Col>
                    <Col span={6}>
                      <span className={`iconfont iconfont-cloud-svg icon-public-${cloud.cloudCode}`} />
                    </Col>
                    <Col span={12}>
                      <Row>
                        <Col span={17}>
                          <FormItem  {...formItemLayout}>
                            <span>{cloud.cloudName}</span><br />
                            <span>已选账号{getAccountSelectNum(cloud.cloudCode)}个</span>
                          </FormItem>
                        </Col>
                        <Col span={6}>
                          <div style={{ textAlign: 'center', marginTop: 10 }} onClick={() => {
                            let temp = [...dropDownsVisible]
                            temp.splice(cloudIndex, 1, !temp[cloudIndex])
                            setDropDownsVisible(temp)
                          }}>
                            <a className="ant-dropdown-link"><DownOutlined /></a>
                          </div>
                        </Col>
                      </Row>
                    </Col>
                  </Row>
                </Dropdown>
              </Col>
            }) : ''
          }
          <Col span={2}>
            <Button type='primary' onClick={() => { handleSubmit() }}>应用</Button>
          </Col>
        </Row>
      </Form>
    </Card>
  );
};

export default HcpHeaderFilter;
